<?php


namespace common\service;

use common\model\ProjectStepCategoryConfirmConfigModel;
use common\model\UserModel as UserModelAlias;
use support\SingletonTrait;

/**
 * 项目延期确认配置
 */
class ProjectStepCategoryConfirmConfigService
{
    use SingletonTrait;

    /**
     * 查询项目延期确认配置列表
     * @param int $projectId
     * @param $type
     * @param int $stepCategoryId
     * @return array
     */
    public function select(int $projectId, $type, int $stepCategoryId)
    {
        $res = [];
        $configList = model(ProjectStepCategoryConfirmConfigModel::class)
            ->alias('c')
            ->join('user u on u.id = c.confirm_user_id')
            ->where(['c.project_id' => $projectId, 'c.type' => $type])
            ->field('c.step_category_id,u.id,u.name,u.avatar,u.union_id,c.step_category_type')
            ->select();
        $configListMap = [];
        foreach ($configList as $configItem) {
            $configListMap[$configItem['step_category_id'] . '#' . $configItem['step_category_type']][] = $configItem;
        }

        $projectStepCategoryConfigList = TemplateService::getInstance()->findStatisticalStepTemplate();

        // 增加角色
//        $projectStepCategoryConfigList = array_merge($projectStepCategoryConfigList, [
//            [
//                'id' => 5, 'name' => '导演', 'code' => 'director', 'children' => [], 'children_ids' => [5], 'is_show' => 'yes', 'link_module_code' => 'role',
//            ],
//            [
//                'id' => 15, 'name' => 'QA', 'code' => 'quality_assurance', 'children' => [], 'children_ids' => [15], 'is_show' => 'yes', 'link_module_code' => 'role',
//            ],
//            [
//                'id' => 16, 'name' => '制片', 'code' => 'executive_producer', 'children' => [], 'children_ids' => [16], 'is_show' => 'yes', 'link_module_code' => 'role',
//            ]
//        ]);
        $projectStepCategoryConfigList = array_map(function ($tmp) {
            $tmp['link_module_code'] = $tmp['link_module_code'] ?? 'step_category';
            return $tmp;
        }, $projectStepCategoryConfigList);

        if ($stepCategoryId > 0) {
            $projectStepCategoryConfigList = array_filter($projectStepCategoryConfigList, function ($i) use ($stepCategoryId) {
                return $i['id'] == $stepCategoryId;
            });
        }
        foreach ($projectStepCategoryConfigList as $projectStepCategoryConfig) {
            $projectStepCategoryConfig['confirm_user_list'] = $configListMap[$projectStepCategoryConfig['id'] . '#' . $projectStepCategoryConfig['link_module_code']] ?? [];
            if ($projectStepCategoryConfig['is_show'] === 'yes') {
                $res[] = $projectStepCategoryConfig;
            }
        }
        return $res;
    }

    /**
     * 保存配置
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function save($data)
    {
        $res = [];
        $currentList = model(ProjectStepCategoryConfirmConfigModel::class)
            ->where([
                'project_id' => $data['project_id'],
                'step_category_id' => $data['step_category_id'],
                'step_category_type' => $data['step_category_type'] ?? 'step_category',
                'type' => $data['type'],
            ])->select();
        $currentList = array_column($currentList, null, 'confirm_user_id');
        if (empty($data['confirm_user_id_list'])) {
            if (!empty($currentList)) {
                $res['deleted'] = model(ProjectStepCategoryConfirmConfigModel::class)
                    ->where(['id' => ['IN', array_column($currentList, 'id')]])
                    ->delete();
            }
        } else {
            $addList = [];
            foreach ($data['confirm_user_id_list'] as $confirmUserId) {
                if (isset($currentList[$confirmUserId])) {
                    continue;
                }
                $addList[] = [
                    'project_id' => $data['project_id'],
                    'step_category_id' => $data['step_category_id'],
                    'step_category_type' => $data['step_category_type'] ?? 'step_category',
                    'type' => $data['type'],
                    'confirm_user_id' => $confirmUserId,
                    'created' => time(),
                    'created_by' => fill_created_by(),
                ];
            }
            $deleteIdList = [];
            foreach ($currentList as $confirmUserId => $current) {
                if (!in_array($confirmUserId, $data['confirm_user_id_list'])) {
                    $deleteIdList[] = $current['id'];
                }
            }
            if (!empty($addList)) {
                $res['added'] = model(ProjectStepCategoryConfirmConfigModel::class)->addAll($addList);
            }
            if (!empty($deleteIdList)) {
                $res['deleted'] = model(ProjectStepCategoryConfirmConfigModel::class)
                    ->where(['id' => ['IN', $deleteIdList]])
                    ->delete();
            }
        }
        return $res;
    }

    /**
     * @param int $projectId
     * @param int $stepCategoryId
     * @param string $type
     * @return array|false|mixed|string
     */
    public function getStepCategoryConfirmUserIdList(int $projectId, int $stepCategoryId, string $type)
    {
        return model(ProjectStepCategoryConfirmConfigModel::class)
            ->where([
                'project_id' => $projectId,
                'step_category_id' => $stepCategoryId,
                'type' => $type,
            ])
            ->field('confirm_user_id')
            ->column('confirm_user_id');
    }

    /**
     * 查询用户在项目里能确认的环节IdList
     * @param mixed $projectId
     * @param int $userId
     * @param string $type
     * @return array|false|mixed|string
     */
    public function getUserCanConfirmStepCategoryIdList($projectId, int $userId, string $type, $field = 'step_category_id')
    {
        $query = model(ProjectStepCategoryConfirmConfigModel::class)
            ->where([
                'project_id' => $projectId,
                'confirm_user_id' => $userId,
                'type' => $type,
            ])
            ->field($field);
        if ($field == 'step_category_id') {
            return $query->column('step_category_id');
        }
        return $query->select();
    }


    /**
     * 多个查找
     * @param $filter
     * @return array|mixed|string
     */
    public function selectUnionIdProjectStepCategoryOptions($filter)
    {
        $projectStepCategoryConfirmConfig = model(ProjectStepCategoryConfirmConfigModel::class)->where($filter)->select();

        if (empty($projectStepCategoryConfirmConfig)) {
            return [];
        }

        $confirmUserId = [];
        foreach ($projectStepCategoryConfirmConfig as $projectStepCategoryConfirmConfigItem) {
            $confirmUserId[$projectStepCategoryConfirmConfigItem['confirm_user_id']] = $projectStepCategoryConfirmConfigItem['confirm_user_id'];
        }


        $userList = model(UserModelAlias::class)->where(['id' => ["IN", array_values($confirmUserId)]])->select();
        $userList = array_column($userList, 'union_id', 'id');

        foreach ($projectStepCategoryConfirmConfig as $index => $projectStepCategoryConfirmConfigItem) {
            $projectStepCategoryConfirmConfigItem['confirm_union_id'] = $userList[$projectStepCategoryConfirmConfigItem['confirm_user_id']];
            $projectStepCategoryConfirmConfig[$index] = $projectStepCategoryConfirmConfigItem;
        }

        return $projectStepCategoryConfirmConfig;
    }

    /**
     * 单个查找
     * @param $filter
     * @return array|mixed|string
     */
    public function findUnionIdProjectProblemStepCategoryOptions($filter)
    {
        $projectStepCategoryConfirmConfig = model(ProjectStepCategoryConfirmConfigModel::class)->where($filter)->find();

        if (empty($projectStepCategoryConfirmConfig)) {
            return [];
        }

        $confirmUserId = $projectStepCategoryConfirmConfig['confirm_user_id'];
        $user = model(UserModelAlias::class)->field("union_id")->find($confirmUserId);
        $projectStepCategoryConfirmConfig['confirm_union_id'] = $user['union_id'];
        return $projectStepCategoryConfirmConfig;
    }
}
